<?php
/**
 * *
 *  * ============================================================================
 *  * Created by PhpStorm.
 *  * User: Ice
 *  * 邮箱: ice@sbing.vip
 *  * 网址: https://sbing.vip
 *  * Date: 2019/9/20 下午5:19
 *  * ============================================================================.
 */

namespace app\common\service\landlord;

use think\Service;
use app\common\service\RedisMake;
use app\common\service\Socket;

/**
 * 斗地主
 */
class Connect extends Index
{

    //系统连接（登陆）  其实应该是登陆房间
    public function connect($data,$fd){
        //房号
        $roomNumber = 'landlord02';
        $uid = $data['user_id']??0;
        if(!$uid){
            swoole_error("参数错误！");
        }
        $username = $data['username']??"";
        if(!$username){
            swoole_error("参数错误！");
        }
        $redis = RedisMake::getRedis();
        //查看redis队列   储存用户Id与fd
        $is_exit = $redis->hExists($roomNumber, $uid);
        //有的话 删除 存入新的fd  没有的话 直接插入
        if($is_exit){
            $redis->hDel($roomNumber, $uid);
        }
        $redis->hSet($roomNumber, $uid, $fd);
        //储存fd连接的游戏房间是哪个
        $is_exit = $redis->hExists('user_game', $fd);
        if($is_exit){
            $redis->hDel('user_game', $fd);
        }
        $roomNumberData = array(
            "type" => $this->gameName,
            "roomNumber" => $roomNumber
        );
        $redis->hSet('user_game', $fd,json_encode($roomNumberData,JSON_UNESCAPED_UNICODE));
        //返回已经连接的用户和准备信息
        $roomData = $redis->get($roomNumber)?:"{}";
        //加入自己的信息   用户名，是否准备
        $roomData = json_decode($roomData,true);
        if($roomData){
            //是否有三个人了
            $num = count($roomData);
            if($num>3){
                return swoole_error("房间已满！");
            }
            $inRoom = false;
            //是否在里面了
            for($n=0;$n<3;$n++){
                if(!$inRoom && isset($roomData[$n]) && $roomData[$n] && isset($roomData[$n]['user_id']) && $roomData[$n]['user_id'] == $uid){
                    //有位置 坐下 未准备
                    $roomData[$n] = array(
                        "user_id" => $uid,
                        "username" => $username,
                        "isready" => 0,
                        "sort" => $n+1,
                        "fd" => $fd,
                    );
                    $inRoom = true;
                    break;
                }
            }
            if(!$inRoom){
                //第一个位置上有人吗
                for($n=0;$n<3;$n++){
                    if(!isset($roomData[$n]) || !$roomData[$n]){
                        //有位置 坐下 未准备
                        $roomData[$n] =
                            array(
                                "user_id" => $uid,
                                "username" => $username,
                                "isready" => 0,
                                "sort" => $n+1,
                                "fd" => $fd,
                            );
                        break;
                    }
                }
            }
        }else{
            $roomData = array(
                0=>array(
                    "user_id" => $uid,
                    "username" => $username,
                    "isready" => 0,
                    "sort" => 1,
                    "fd" => $fd,
                ),
            );
        }
        //存入redis
        $redis->set($roomNumber,json_encode($roomData,JSON_UNESCAPED_UNICODE));
        //通知所有已经连接的用户  有人连接进来了
        foreach($roomData as $v){
            $message = swoole_success($username." 进入了房间",$roomData,"enter_room");
            Socket::sendMsg($message,$v['fd']);
        }
        return swoole_success("连接成功！");
    }


    //退出
    public function close($roomNumber,$fd){
        $roomNumber = $roomNumber??"";
        if(!$roomNumber || !$fd){
            //写日志
            return false;
        }
        //查看redis队列
        $redis = RedisMake::getRedis();
        //返回已经连接的用户和准备信息
        $roomData = $redis->get($roomNumber)?:"{}";
        //删除自己的信息
        $roomData = json_decode($roomData,true);
        if($roomData){
            $uid = 0;
            $username = "";
            //是否在里面了
            for($n=0;$n<3;$n++){
                if(!$uid && isset($roomData[$n]) && $roomData[$n] && isset($roomData[$n]['fd']) && $roomData[$n]['fd'] == $fd){
                    //获取uid  删除roomData
                    $uid = $roomData[$n]['user_id']??0;
                    $username = $roomData[$n]['username']??'';
                    unset($roomData[$n]);
                    break;
                }
            }
            //存入redis
            $redis->set($roomNumber,json_encode($roomData,JSON_UNESCAPED_UNICODE));
            if($uid && $username){
                //通知所有已经连接的用户  有人退出
                foreach($roomData as $v){
                    $message = swoole_success($username." 退出了房间",$roomData,"enter_room");
                    Socket::sendMsg($message,$v['fd']);
                }
                //删除redis中的自己用户信息
                $is_exit = $redis->hExists($roomNumber, $uid);
                //有的话 删除 存入新的fd  没有的话 直接插入
                if($is_exit){
                    $redis->hDel($roomNumber, $uid);
                }
                return true;
            }
        }
        //写日志
        return false;
    }

    //ready
    public function ready($data,$fd){
        //房号
        $flag = false;
        $result = swoole_error("参数错误！");
        $roomNumber = 'landlord02';
        $ready_num = 0;
        $uid = $data['user_id']??0;
        if(!$uid){
            swoole_error("参数错误！");
        }
        $redis = RedisMake::getRedis();
        //返回已经连接的用户和准备信息
        $roomData = $redis->get($roomNumber)?:"{}";
        //加入自己的信息   用户名，是否准备
        $roomData = json_decode($roomData,true);
            $ready_num = 0;
        if($roomData){
            $inRoom = false;
            //是否在里面了
            for($n=0;$n<3;$n++){
                if(!$inRoom && isset($roomData[$n]) && $roomData[$n] && isset($roomData[$n]['user_id']) && $roomData[$n]['user_id'] == $uid){
                    $roomData[$n]["isready"] = 1;
                    $roomData[$n]["sort"] = $n+1;
                    $roomData[$n]["fd"] = $fd;
                    $inRoom = true;
                    $flag = true;
                    break;
                }
                if(isset($roomData[$n]) && $roomData[$n] && isset($roomData[$n]['isready']) && $roomData[$n]['isready'] == 1){
                    $ready_num++;
                }
            }
            if(!$inRoom){
                $result = swoole_error("您已经掉线，请刷新！");
            }
        }else{
            $result = swoole_error("您已经掉线，请刷新！");
        }
        //存入redis
        $redis->set($roomNumber,json_encode($roomData,JSON_UNESCAPED_UNICODE));
        //通知所有已经连接的用户  有人连接进来了
        foreach($roomData as $v){
            $message = swoole_success("有人准备了",$roomData,"user_ready");
            Socket::sendMsg($message,$v['fd']);
        }
        if($flag){
            //如果全都准备了  开始游戏
            if($ready_num >=3){
                $game = new Game($this->app);
                $result = $game->start($roomNumber);
                return $result;
            }else{
                $result = swoole_success("准备成功！");
            }
        }
        return $result;
    }
}
